$(function () {

    // init date tables
    var dbinfoTable = $("#dbinfo_list").dataTable({
        "deferRender": true,
        "processing" : true,
        "serverSide": true,
        "ajax": {
            url: base_url + "/dbinfo/pageList",
            type:"post",
            data : function ( d ) {
                var obj = {};
                obj.name = $('#dbname').val();
                obj.belong = $('#belong').val();
                obj.remark = $('#remark').val();
                obj.start = d.start;
                obj.length = d.length;
                return obj;
            }
        },
        "searching": false,
        "ordering": false,
        //"scrollX": true,	// scroll x，close self-adaption
        "columns": [
            {
                "data": 'id',
                "bSortable": false,
                "visible" : true,
                "width":'8%'
            },
            {
                "data": 'name',
                "visible" : true,
                "width":'10%'
            },
            {
                "data": 'belong',
                "visible" : true,
                "width":'10%'
            },
            {
                "data": 'dbType',
                "visible" : true,
                "width":'10%',
                "render" : function (data, type, row) {
                    if(data==1) {
                        return "MYSQL";
                    } else if(data==2) {
                        return "Oracle";
                    } else if(data==3) {
                        return "MongoDB"
                    } else {
                        return "MYSQL";
                    }
                }
            },
            {
                "data": 'createTime',
                "visible" : true,
                "width":'15%',
                "render": function ( data, type, row ) {
                    return data?moment(new Date(data)).format("YYYY-MM-DD HH:mm:ss"):"";
                }
            },
            {
                "data": 'updateTime',
                "visible" : true,
                "width":'15%',
                "render": function ( data, type, row ) {
                    return data?moment(new Date(data)).format("YYYY-MM-DD HH:mm:ss"):"";
                }
            },
            {
                "data": I18n.system_opt ,
                "width":'10%',
                "render": function ( data, type, row ) {
                    return function(){

                        // data
                        tableData['key'+row.id] = row;

                        // opt
                        var html = '<div class="btn-group">\n' +
                            '     <button type="button" class="btn btn-primary btn-sm">'+ I18n.system_opt +'</button>\n' +
                            '     <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">\n' +
                            '       <span class="caret"></span>\n' +
                            '       <span class="sr-only">Toggle Dropdown</span>\n' +
                            '     </button>\n' +
                            '     <ul class="dropdown-menu" role="menu" _id="'+ row.id +'" >\n' +
                            '       <li><a href="javascript:void(0);" class="db_operate" _type="db_detail" >'+ I18n.db_detail +'</a></li>\n' +
                            '       <li><a href="javascript:void(0);" class="db_operate" _type="db_update" >'+ I18n.db_update +'</a></li>\n' +
                            '       <li class="divider"></li>\n' +
                            '       <li><a href="javascript:void(0);" class="db_operate" _type="db_copy">'+ I18n.db_copy +'</a></li>\n' +
                            '       <li><a href="javascript:void(0);" class="db_operate" _type="db_delete">'+ I18n.db_delete +'</a></li>\n' +
                            '     </ul>\n' +
                            '   </div>';

                        return html;
                    };
                }
            }
        ],
        "language" : {
            "sProcessing" : I18n.dataTable_sProcessing ,
            "sLengthMenu" : I18n.dataTable_sLengthMenu ,
            "sZeroRecords" : I18n.dataTable_sZeroRecords ,
            "sInfo" : I18n.dataTable_sInfo ,
            "sInfoEmpty" : I18n.dataTable_sInfoEmpty ,
            "sInfoFiltered" : I18n.dataTable_sInfoFiltered ,
            "sInfoPostFix" : "",
            "sSearch" : I18n.dataTable_sSearch ,
            "sUrl" : "",
            "sEmptyTable" : I18n.dataTable_sEmptyTable ,
            "sLoadingRecords" : I18n.dataTable_sLoadingRecords ,
            "sInfoThousands" : ",",
            "oPaginate" : {
                "sFirst" : I18n.dataTable_sFirst ,
                "sPrevious" : I18n.dataTable_sPrevious ,
                "sNext" : I18n.dataTable_sNext ,
                "sLast" : I18n.dataTable_sLast
            },
            "oAria" : {
                "sSortAscending" : I18n.dataTable_sSortAscending ,
                "sSortDescending" : I18n.dataTable_sSortDescending
            }
        }
    });

    // table data
    var tableData = {};

    // search btn
    $('#searchBtn').on('click', function(){
        dbinfoTable.fnDraw(false);
    });


    // add
    $(".add").click(function(){
        $('#addModal').modal({backdrop: false, keyboard: false}).modal('show');
    });
    var addModalValidate = $("#addModal .form").validate({
        errorElement : 'span',
        errorClass : 'help-block',
        focusInvalid : true,
        rules : {
            name : {
                required : true,
                maxlength: 20
            },
            dbUsername : {
                required : true,
                maxlength: 50
            },
            dbPassword : {
                required : true,
                maxlength: 50
            },
            dbUrl : {
                required: true,
                maxlength: 200
            },
            dbName : {
                required: true,
                maxlength: 32
            }
        },
        messages : {
            name : {
                required : I18n.system_please_input + I18n.db_field_name
            },
            dbUsername : {
                required : I18n.system_please_input + I18n.db_field_username
            },
            dbPassword : {
                required : I18n.system_please_input + I18n.db_field_password
            },
            dbUrl : {
                required : I18n.system_please_input + I18n.db_field_url
            },
            dbName : {
                required : I18n.system_please_input + I18n.db_field_dbName
            }
        },
        highlight : function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        success : function(label) {
            label.closest('.form-group').removeClass('has-error');
            label.remove();
        },
        errorPlacement : function(error, element) {
            element.parent('div').append(error);
        },
        submitHandler : function(form) {

            $.post(base_url + "/dbinfo/add",  $("#addModal .form").serialize(), function(data, status) {
                if (data.code == "200") {
                    $('#addModal').modal('hide');
                    layer.open({
                        title: I18n.system_tips ,
                        btn: [ I18n.system_ok ],
                        content: I18n.system_add_suc ,
                        icon: '1',
                        end: function(layero, index){
                            dbinfoTable.fnDraw();
                            //window.location.reload();
                        }
                    });
                } else {
                    layer.open({
                        title: I18n.system_tips ,
                        btn: [ I18n.system_ok ],
                        content: (data.msg || I18n.system_add_fail),
                        icon: '2'
                    });
                }
            });
        }
    });
    $("#addModal").on('hide.bs.modal', function () {
        $("#addModal .form")[0].reset();
        addModalValidate.resetForm();
        $("#addModal .form .form-group").removeClass("has-error");
        $(".remote_panel").show();	// remote

        $("#addModal .form input[name='executorHandler']").removeAttr("readonly");
    });

    $("#addModal button[name='testDbInfo']").on('click',function () {
        var typeName = I18n.system_testDbInfo;

        $.post(base_url + "/dbinfo/testNewDbInfo",  $("#addModal .form").serialize(), function(data, status) {
            console.log(data);
            if (data.code == "200") {
                layer.msg( typeName + I18n.system_success );
            } else {
                layer.msg( data.msg || typeName + I18n.system_fail );
            }
        });
    });
    //
    $("#addModal select[name='dbDriver']").on('change', function(){
        if($(this).val() == "") {
            $("#addModal input[name='dbUrl']").val("");
        } else if($(this).val() == "com.mysql.jdbc.Driver" && $("#addModal input[name='dbUrl']").val() == "") {
            $("#addModal input[name='dbUrl']").val("jdbc:mysql://127.0.0.1:3306/dbName?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=CTT");
        } else if($(this).val() == "com.mysql.cj.jdbc.Driver" && $("#addModal input[name='dbUrl']").val() == "") {
            $("#addModal input[name='dbUrl']").val("jdbc:mysql://127.0.0.1:3306/dbName?userSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT");
        } else if($(this).val() == "oracle.jdbc.driver.OracleDriver" && $("#addModal input[name='dbUrl']").val() == "") {
            $("#addModal input[name='dbUrl']").val("jdbc:oracle:thin:@127.0.0.1:1521:dbName");
        } else if($(this).val() == "com.microsoft.jdbc.sqlserver.SQLServerDriver" && $("#addModal input[name='dbUrl']").val() == "") {
            $("#addModal input[name='dbUrl']").val("jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=dbName;User=sa;Password=pwd");
        }
    });

    // job operate
    $("#dbinfo_list").on('click', '.db_operate',function() {
        var typeName;
        var url;
        var needFresh = false;

        var type = $(this).attr("_type");
        if ("db_detail" == type) {
            typeName = I18n.db_detail ;
            url = base_url + "/dbinfo/detail";
            needFresh = false;
        } else if ("db_update" == type) {
            typeName = I18n.db_update ;
            url = base_url + "/dbinfo/detail";
            needFresh = false;
        } else if ("db_copy" == type) {
            typeName = I18n.db_copy;
            url = base_url + "/dbinfo/copy";
            needFresh = true;
        } else if ("db_delete" == type) {
            typeName = I18n.db_delete ;
            url = base_url + "/dbinfo/delete";
            needFresh = true;
        } else {
            return;
        }

        var id = $(this).parents('ul').attr("_id");

        if ("db_detail" == type || "db_update" == type) {
            $.ajax({
                type : 'POST',
                url : url,
                data : {
                    "id" : id
                },
                dataType : "json",
                success : function(data){
                    console.log(data);
                    if (data.code == 200) {
                        if ("db_detail" == type) {
                            var content = data.content;
                            var dbType = getDbType(content.dbType);
                            $("#detailModal .form input[name='id']").val( content.id );

                            $("#detailModal .form input[name='dbType']").val(dbType);
                            $("#detailModal .form input[name='name']").val(content.name);
                            $("#detailModal .form input[name='dbUserName']").val(content.dbUserName);
                            $("#detailModal .form input[name='dbPassword']").val(content.dbPassword);
                            $("#detailModal .form input[name='dbDriver']").val(content.dbDriver);
                            $("#detailModal .form input[name='dbUrl']").val(content.dbUrl);
                            $("#detailModal .form input[name='belong']").val(content.belong);
                            $("#detailModal .form input[name='remark']").val(content.remark);
                            $("#detailModal .form input[name='dbName']").val(content.dbName);
                            $("#detailModal .form input[name='mongodbPort']").val(content.mongodbPort);
                            $("#detailModal .form input[name='mongodbDatabase']").val(content.mongodbDatabase);
                            $("#detailModal .form input[name='mongodbHost']").val(content.mongodbHost);
                            // show
                            $('#detailModal').modal({backdrop: false, keyboard: false}).modal('show');
                        } else if ("db_update" == type) {
                            var content = data.content;

                            $("#updateModal .form input[name='id']").val( content.id );
                            $('#updateModal .form select[name=dbType] option[value='+ content.dbType +']').prop('selected', true);

                            $("#updateModal .form input[name='dbType']").val(dbType);
                            $("#updateModal .form input[name='name']").val(content.name);
                            $("#updateModal .form input[name='dbUserName']").val(content.dbUserName);
                            $("#updateModal .form input[name='dbPassword']").val(content.dbPassword);
                            /*$("#updateModal .form input[name='dbDriver']").val(content.dbDriver);*/
                            $("#updateModal .form input[name='dbUrl']").val(content.dbUrl);
                            $("#updateModal .form select[name=dbDriver] option[value='"+ content.dbDriver +"']").prop('selected', true);
                            $("#updateModal .form input[name='belong']").val(content.belong);
                            //$('#updateModal .form select[name=belong] option[value='+ content.belong +']').prop('selected', true);
                            $("#updateModal .form input[name='remark']").val(content.remark);
                            $("#updateModal .form input[name='dbName']").val(content.dbName);
                            $("#updateModal .form input[name='mongodbPort']").val(content.mongodbPort);
                            $("#updateModal .form input[name='mongodbDatabase']").val(content.mongodbDatabase);
                            $("#updateModal .form input[name='mongodbHost']").val(content.mongodbHost);
                            // show
                            $('#updateModal').modal({backdrop: false, keyboard: false}).modal('show');
                        }
                    } else {
                        layer.msg( data.msg || typeName + I18n.system_fail );
                    }
                }
            });
        } else {
            layer.confirm( I18n.system_ok + typeName + '?', {
                icon: 3,
                title: I18n.system_tips ,
                btn: [ I18n.system_ok, I18n.system_cancel ]
            }, function(index){
                layer.close(index);

                $.ajax({
                    type : 'POST',
                    url : url,
                    data : {
                        "id" : id
                    },
                    dataType : "json",
                    success : function(data){
                        if (data.code == 200) {
                            if ("db_delete" == type || "db_copy" == type) {
                                layer.msg( typeName + I18n.system_success );
                            }

                            if (needFresh) {
                                //window.location.reload();
                                dbinfoTable.fnDraw(false);
                            }
                        } else {
                            layer.msg( data.msg || typeName + I18n.system_fail );
                        }
                    }
                });
            });
        }


    });

    $("#detailModal button[name='testDbInfo']").on('click',function () {
        var typeName = I18n.system_testDbInfo;
        $.ajax({
            type : 'POST',
            url : base_url + "/dbinfo/testDbInfoById",
            data : {
                "id" : $("#detailModal .form input[name='id']").val()
            },
            dataType : "json",
            success : function(data){
                console.log(data);
                if (data.code == 200) {
                    layer.msg( typeName + I18n.system_success );
                } else {
                    layer.msg( data.msg || typeName + I18n.system_fail );
                }
            }
        });
    });

    var updateModalValidate = $("#updateModal .form").validate({
        errorElement : 'span',
        errorClass : 'help-block',
        focusInvalid : true,
        rules : {
            name : {
                required : true,
                maxlength: 20
            },
            dbUsername : {
                required : true,
                maxlength: 50
            },
            dbPassword : {
                required : true,
                maxlength: 50
            },
            dbUrl : {
                required: true,
                maxlength: 200
            },
            dbName : {
                required: true,
                maxlength: 32
            },
            belong: {
                required: true,
                maxlength: 32
            }
        },
        messages : {
            name : {
                required : I18n.system_please_input + I18n.db_field_name
            },
            dbUsername : {
                required : I18n.system_please_input + I18n.db_field_username
            },
            dbPassword : {
                required : I18n.system_please_input + I18n.db_field_password
            },
            dbUrl : {
                required : I18n.system_please_input + I18n.db_field_driver
            },
            dbName : {
                required : I18n.system_please_input + I18n.db_field_dbName
            },
            belong: {
                required : I18n.system_please_input + I18n.db_field_belong
            }
        },
        highlight : function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        success : function(label) {
            label.closest('.form-group').removeClass('has-error');
            label.remove();
        },
        errorPlacement : function(error, element) {
            element.parent('div').append(error);
        },
        submitHandler : function(form) {

            $.post(base_url + "/dbinfo/update",  $("#updateModal .form").serialize(), function(data, status) {
                if (data.code == "200") {
                    $('#updateModal').modal('hide');
                    layer.open({
                        title: I18n.system_tips ,
                        btn: [ I18n.system_ok ],
                        content: I18n.system_update_suc ,
                        icon: '1',
                        end: function(layero, index){
                            dbinfoTable.fnDraw();
                            //window.location.reload();
                        }
                    });
                } else {
                    layer.open({
                        title: I18n.system_tips ,
                        btn: [ I18n.system_ok ],
                        content: (data.msg || I18n.system_update_fail),
                        icon: '2'
                    });
                }
            });
        }
    });
    $("#updateModal").on('hide.bs.modal', function () {
        $("#updateModal .form")[0].reset()
    });

    $("#updateModal button[name='testDbInfo']").on('click',function () {
        var typeName = I18n.system_testDbInfo;
        $.ajax({
            type : 'POST',
            url : base_url + "/dbinfo/testDbInfoById",
            data : {
                "id" : $("#updateModal .form input[name='id']").val()
            },
            dataType : "json",
            success : function(data){
                if (data.code == 200) {
                    layer.msg( typeName + I18n.system_success );
                } else {
                    layer.msg( data.msg || typeName + I18n.system_fail );
                }
            }
        });
    });
});

function getBelongRemark(data) {
    if(data == null || data == undefined || data == "") return "";
    var temp = "";
    $("input[name='belongEnum']").each(function (index, ele) {
        var v = $(this).val();
        if(v != null && v != undefined && v != "") {
            if(v.indexOf(data)!= -1) {
                temp = v.split('-')[1];
                return false;
            }
        }
    });
    return temp;
}

function getDbType(data) {
    if(data==1) {
        return "MYSQL";
    } else if(data==2) {
        return "Oracle";
    } else if(data==3) {
        return "MongoDB"
    } else if(data==4) {
        return "SQLServer"
    }  else {
        return "";
    }
}